<template>
  <div class="bgBackground" style="overflow-y: auto;">
    <div style="height: 55px;width: 100%; overflow-x: paged-x;min-width: 600px">
      <el-col :span="3" :offset="1">
        <div class="title_div" style="width: 200px" @click="toHome()">
          <h2 class="title_h2">
            <i class="el-icon-s-home"></i>
            弄个房租</h2>
        </div>
      </el-col>
      <el-col :span="5" :offset="14">
        <div v-if="!user.userName" style="margin-top: 10px" @click="toLoginAndRegister()">
          <el-avatar :size="40" src="../../../../static/image/noLoginHeadImage.png"></el-avatar>
          <span class="login_register" style="color: white;font-size: 18px">登录/注册</span>
        </div>
        <div v-else style="margin-top: 10px">
          <el-avatar :size="40"
                     :src="user.headImage?'http://192.168.123.150/'+user.headImage:'../../../../static/image/noLoginHeadImage.png'"></el-avatar>
<!--          <el-popover-->
<!--            placement="bottom"-->
<!--            width="60px"-->
<!--            style="padding: 0px;"-->
<!--            trigger="hover">-->
<!--            <ul style="list-style: none;padding: 0px 20px 0px 20px">-->
<!--              <el-badge :value="12" class="item">-->
<!--                <li style="margin-top: 5px">消息</li>-->
<!--              </el-badge>-->
<!--              <li style="margin-top: 5px" @click="logout()">退出</li>-->
<!--            </ul>-->
<!--            &lt;!&ndash;              <el-button >click 激活</el-button>&ndash;&gt;-->
<!--            <span class="login_register" slot="reference"-->
<!--                  style="color: black;font-size: 18px">{{ user.nickname }}</span>-->
<!--          </el-popover>-->
        </div>
      </el-col>
    </div>
    <div style="padding: 60px 60px 0px 60px ; height:  600px">
      <el-tabs tab-position="left" style="height: 600px;">
        <el-tab-pane label="基础信息">
          <el-descriptions class="margin-top" title="基础信息" :column="2" border>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-user"></i>
                用户名
              </template>
              {{ user.userName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-edit"></i>
                密码
              </template>
              ******
            </el-descriptions-item>
            <el-descriptions-item label="昵称">
              <el-input v-model="nickname" v-if="showNickName" style="width: 300px">
                <el-button-group slot="append" style="width: 60px">
                  <el-button icon="el-icon-close" style="width: 30px;color: red" @click="showNickName=false"></el-button>
                  <el-button icon="el-icon-check" style="width: 30px;color: green" @click="editNickNmae()"></el-button>
                </el-button-group>
              </el-input>
              <el-button v-else @dblclick.native="changeNickname()" type="text">{{ user.nickname }}</el-button>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-s-platform"></i>
                邮箱
              </template>
              {{ user.email }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ user.createTime }}
            </el-descriptions-item>
            <el-descriptions-item label="上次登录时间">
              {{ user.lastLoginTime }}
            </el-descriptions-item>
            <el-descriptions-item label="头像">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :auto-upload="false"
                action=""
                :on-change="fileChange">
                <img v-if="user.headImage" :src="'http://192.168.123.150/'+user.headImage" style="height: 178px;width: 178px;">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="真实资料">
          <el-descriptions class="margin-top" title="真实资料" :column="2" border>
            <template slot="extra">
              <el-button type="primary" @click="updateRealUser()" size="small">修改</el-button>
            </template>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-user"></i>
                姓名
              </template>
              {{ realUser.realName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-phone"></i>
                手机号
              </template>
              {{ realUser.moblie }}
            </el-descriptions-item>
            <el-descriptions-item label="身份证号">
              {{ realUser.idCard }}
            </el-descriptions-item>
            <el-descriptions-item label="详细位置">
              {{ realUser.address }}
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
      </el-tabs>
      <el-dialog
        :before-close="handleClose"
        title="修改真实信息"
        :visible.sync="dialogVisible"
      >
        <div style="height: 400px">
          <el-form :rules="rules" :model="realUser" ref="realUser">
            <el-form-item label="姓名" prop="realName">
              <el-input :disabled="isEdit" v-model="realUser.realName"></el-input>
            </el-form-item>
            <el-form-item label="身份证号" prop="idCard">
              <el-input :disabled="isEdit" v-model="realUser.idCard"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="moblie">
              <el-input v-model="realUser.moblie"></el-input>
            </el-form-item>
            <el-form-item label="位置" prop="address">
              <el-input v-model="realUser.address"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span style="float: bottom; margin-bottom: 30px" slot="footer" class="dialog-footer">
                                <el-button type="primary" @click="sureRealUser()">确 定</el-button>
                              </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import backImage from "../../static/image/home_beijing.png";

export default {
  name: "PersonalCenterModule",
  data() {
    var validateIdCard = async (rule, value, callback) => {
      if (this.realUser.realName === '') {
        this.$refs.realUser.validateField("realName");
      } else {
        await this.$axios({
          url: '/realUser/verifyIdCard',
          method: 'get',
          params: {
            name: this.realUser.realName,
            idCard: value
          }
        }).then(res => {
          // let response = JSON.parse(res.data.data)
          console.log(res)
          if (res.data.data != "0") {
            return callback(new Error(response.Description))
          } else {
            return callback()
          }
        })
      }
      return callback()
    };
    var validateMoblie = async (rule, value, callback) => {
      if (this.realUser.realName === '') {
        this.$refs.realUser.validateField("realName")
      } else {
        await this.$axios({
          url: "/realUser/validateMoblie",
          method: 'get',
          params: {
            name: this.realUser.realName,
            moblie: this.realUser.moblie
          }
        }).then(res => {
          let response = JSON.parse(res.data.data)
          if (res.data.data != "0") {
            return callback(new Error(response.Description))
          } else {
            return callback()
          }
        })
      }
    };
    var validateRealName = (rule, value, callback) => {
      this.$refs.realUser.validateField("idCard")
      return callback()
    };
    return {
      rules: {
        idCard: [{
          required: true,
          message: '请填写证件号码',
          trigger: 'blur'
        },
          {
            pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
            message: '证件号码格式有误！',
            trigger: 'blur'
          },
          {
            validator: validateIdCard,
            trigger: 'blur'
          }
        ],
        moblie: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            pattern: /^0{0,1}(13[0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$/,
            message: '手机号格式不对',
            trigger: 'blur'
          },
          {
            validator: validateMoblie,
            trigger: 'blur'
          }],
        realName: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }, {
            validator: validateRealName,
            trigger: 'blur'
          }
        ],
      },
      dialogVisible: false,
      dialogImageUrl: '',
      id: '',
      isEdit: false,
      editUserInfo: {
        oldPassword: '',
        newPassword: '',
        reNewPassword: '',
        headImage: []
      },
      user: {
        userName: '',
        headImage: [],
        id: '',
        email: '',
        createTime: '',
        lastLoginTime: '',
        nickname: '',
      },
      realUser: {
        id: '',
        realName: '',
        moblie: '',
        idCard: '',
        address: '',
        userId: '',
      },
      nickname:'',
      showNickName: false,
      password:'',
      showPassword: false,
      prewList: [],
      background: {
        // 背景图片地址
        backgroundImage: `url(${backImage})`,
        width: '100%',
        height: '100%',
        position: 'fixed',

        // 背景图片是否重复
        backgroundRepeat: 'no-repeat',
        // 背景图片大小
        backgroundSize: '100% 100%',
        // 背景颜色
        backgroundColor: '#2b2b2b',
        // // 背景图片位置
        // backgroundPosition: 'center center',
      }

    }
  },
  mounted() {
    this.getUserInfo()
  },
  methods: {
    toHome() {
      this.$router.push({path: "/"})
    },
    sureRealUser() {
      if (!this.isEdit) {
        this.$refs.realUser.validate((valid) => {
          if (valid) {
            this.$axios({
              url: "/realUser/updateRealUser",
              method: "post",
              data: {
                ...this.realUser
              }
            }).then(res => {
              if (res.data.code === 200) {
                this.dialogVisible = false
                this.getRealUserInfo();
                this.$message.success("操作成功！")
              } else {
                this.$message.error("操作失败，请联系管理员！")
              }
            })
          } else {
            return false;
          }
        })
      } else {
        this.$refs.realUser.validateField(["moblie"], (valid) => {
          if (!valid) {
            this.$axios({
              url: "/realUser/updateRealUser",
              method: "post",
              data: {
                ...this.realUser
              }
            }).then(res => {
              if (res.data.code === 200) {
                this.dialogVisible = false
                this.getRealUserInfo();
                this.$message.success("操作成功！")
              } else {
                this.$message.error("操作失败，请联系管理员！")
              }
            })
          }
        });
      }

    },
    updateRealUser() {
      this.dialogVisible = true
    },
    handleClose() {
      this.dialogVisible = false
      this.toRestFild("realUser")
      this.getRealUserInfo()
    },
    getRealUserInfo() {
      let userId = this.id
      this.$axios({
        url: "/realUser/getRealUserInfo",
        method: "get",
        params: {
          userId: userId
        }
      }).then(res => {
        if (res.data.code === 200) {
          let data = res.data.data
          if (data !== null) {
            this.$nextTick(() => {
              this.realUser = {
                id: data.id,
                idCard: data.idCard,
                moblie: data.moblie,
                realName: data.realName,
                address: data.address,
                userId: userId,
              }
            })
            this.isEdit = true
          } else {
            this.realUser = {
              id: '',
              realName: '',
              moblie: '',
              idCard: '',
              address: '',
              userId: userId
            }
          }
        } else {
          this.$message.error("操作失败，请联系管理员！")
        }
      })
    },
    fileChange(file) {
      let formData = new FormData()
      formData.append("userId", this.user.id)
      formData.append("file", file.raw)
      this.$axios({
        method: "post",
        headers: {
          "Content-Type": "multipart/form-data"
        },
        data: formData,
        url: "/myUser/editHeadImage"
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success("修改成功，请退出后重新登录后生效！")
        } else {
          this.$message.error("修改失败！")
        }
      })

    },
    getUserInfo() {
      this.$axios({
        method: "get",
        url: "/getUserInfo"
      }).then(res => {
        if (res.data.code === 200) {
          let user = res.data.data
          this.id = user.id
          this.$store.commit("setUserId", user.id)
          this.$store.commit("setNickname", user.nickname)
          this.$store.commit("setName", user.username)
          this.$store.commit("setHeadImage", user.headImage)
          this.$store.commit("setRoleList", JSON.stringify(user.roleList))
          sessionStorage.setItem("roleList", user.roleList)
        }
      })
    },
    getMyUser() {
      this.$axios({
        url: '/getMyUser',
        method: 'get',
        params: {
          id: this.id
        }
      }).then(res => {
        if (res.data.code === 200) {
          let data = res.data.data
          this.user = {
            userName: data.username,
            id: data.id,
            email: data.email,
            createTime: data.createTime,
            lastLoginTime: data.lastLoginTime,
            nickname: data.nickname,
            headImage: data.headImage
          }
          this.prewList = []
          this.prewList.push("http://192.168.123.150" + data.headImage)
        } else {
          this.$message.error("操作出错，请联系管理员！")
        }
      })
    },
    logout() {
      this.$store.dispatch("logout");
      localStorage.removeItem("Authorization");
      this.$router.push({path: "/"})
    },
    toRestFild(ref) {
      this.$nextTick(() => {
        this.$refs[ref].resetFields()
      })
    },
    changeNickname() {
      this.showNickName = true
      this.nickname = this.user.nickname
    },
    editNickNmae(){
      this.$axios({
        url:'/editNickname',
        method: "put",
        params:{
          nickname: this.nickname,
          id: this.user.id,
        }
      }).then(res=>{
        if (res.data.code===200){
          this.$message.success("操作成功！");
          this.getMyUser()
          this.showNickName = false
        }else{
          this.$message.error("操作失败，请联系管理员处理！");
        }
      })
    }

  },
  watch: {
    id(val) {
      if (val !== '') {
        this.getMyUser()
        this.getRealUserInfo()
      }
    },

  }
}
</script>

<style scoped>
html,
body,
.bgBackground {
  width: 100%;
  height: 500px
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.title_div :hover {
  cursor: pointer;
}

</style>
